package com.gulimall.product.acpect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author HT
 * @date 2020/2/3 9:04
 **/
@Aspect
@Component
@Slf4j
public class WebLogAspect {
    /**
     * 定义切入点，切入点为com.example.aop下的所有函数
     */
    @Pointcut("execution(public * com.gulimall.*.controller.*.*(..))")
    public void webLogAspect() {
    }

    /**
     * 前置通知：在连接点之前执行的通知
     *
     * @param joinPoint 连接点
     */
    @Before("webLogAspect()")
    public void doBefore(JoinPoint joinPoint) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        log.info("------------");
        log.info("Url : " + request.getRequestURL().toString());
        log.info("Http_Method : " + request.getMethod());
        log.info("Ip : " + request.getRemoteAddr());
        log.info("Class_Method : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("Args : " + Arrays.toString(joinPoint.getArgs()));
        log.info("------------");
    }

    @AfterReturning(returning = "restResult", pointcut = "webLogAspect()")
    public void doAfterReturning(Object restResult) {
        log.info("------------");
        log.info("------------");
    }

}

